package com.zxgj.datadirect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zxgj.datadirect.entity.DataDirectTodo;
import com.zxgj.datadirect.mapper.DataDirectTodoMapper;
import com.zxgj.datadirect.service.DataDirectTodoService;
import com.zxgj.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 我的待办服务实现类（对应《实施清单》"我的待办管理"功能，处理外来资源申请审核待办）
 */
@Slf4j
@Service
public class DataDirectTodoServiceImpl extends ServiceImpl<DataDirectTodoMapper, DataDirectTodo>
        implements DataDirectTodoService {

    @Autowired
    private DataDirectTodoMapper todoMapper;

    /**
     * 分页查询待办列表
     * @param page 分页参数
     * @param assignee 经办人
     * @param status 状态
     * @return 分页待办数据
     */
    @Override
    public Page<DataDirectTodo> getTodoPage(Page<DataDirectTodo> page, String assignee, String status) {
        LambdaQueryWrapper<DataDirectTodo> queryWrapper = new LambdaQueryWrapper<>();

        // 设置查询条件
        if (StringUtils.isNotEmpty(assignee)) {
            queryWrapper.eq(DataDirectTodo::getAssignee, assignee);
        }
        if (StringUtils.isNotEmpty(status)) {
            queryWrapper.eq(DataDirectTodo::getStatus, status);
        }

        // 按创建时间倒序排列
        queryWrapper.orderByDesc(DataDirectTodo::getCreateTime);

        return this.page(page, queryWrapper);
    }

    /**
     * 查看待办详情
     * @param id 待办ID
     * @return 待办详情
     */
    @Override
    public DataDirectTodo getTodoDetail(Long id) {
        if (id == null) {
            throw new IllegalArgumentException("待办ID不能为空");
        }

        return this.getById(id);
    }

    /**
     * 批量标记待办已读
     * @param applyNos 申请单号列表
     * @param userId 操作人ID
     * @return 标记成功条数
     */
    @Override
    @Transactional
    public int markTodoRead(List<String> applyNos, Long userId) {
        if (applyNos == null || applyNos.isEmpty()) {
            return 0;
        }

        if (userId == null) {
            throw new IllegalArgumentException("操作人ID不能为空");
        }

        int successCount = 0;

        for (String applyNo : applyNos) {
            try {
                // 查询待办记录
                LambdaQueryWrapper<DataDirectTodo> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(DataDirectTodo::getApplyNo, applyNo);
                
                DataDirectTodo todo = this.getOne(wrapper);

                if (todo != null && !todo.getIsRead()) {
                    // 更新已读状态
                    todo.setIsRead(true);
                    todo.setReadTime(new Date());
                    todo.setUpdateBy(userId.toString());
                    todo.setUpdateTime(new Date());

                    boolean result = this.updateById(todo);
                    if (result) {
                        successCount++;
                    }
                }
            } catch (Exception e) {
                // 记录日志，继续处理其他记录
                log.error("标记待办已读失败，申请单号: {}, 错误信息: {}", applyNo, e.getMessage());
                continue; // 继续处理其他记录
            }
        }

        return successCount;
    }

    /**
     * 统计待办数量（用于待办红点）
     * @param assignee 经办人
     * @return 待办数量
     */
    @Override
    public int countTodo(String assignee) {
        if (StringUtils.isEmpty(assignee)) {
            return 0;
        }

        LambdaQueryWrapper<DataDirectTodo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DataDirectTodo::getAssignee, assignee);
        queryWrapper.eq(DataDirectTodo::getIsRead, false); // 未读状态

        return (int) this.count(queryWrapper);
    }
}
